<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- 添加分类 -->
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" @click="showAddCateDialog">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <tree-table
        class="tree-table"
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
      >
        <template slot="isok" slot-scope="scope">
          <i class="el-icon-success" v-if="!scope.row.cat_delete" style="color:green"></i>
          <i class="el-icon-error" v-else style="color:red"></i>
        </template>
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag type="warning" v-else-if="scope.row.cat_level === 2">三级</el-tag>
        </template>
        <template slot="action" slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" @click="showEditCateDialog(scope.row.cat_id)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" @click="deleteCate(scope.row)">删除</el-button>
        </template>
      </tree-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 3, 5, 6, 8, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- "添加分类"对话框 -->
    <el-dialog title="添加分类" :visible.sync="addCateDialogVisible" width="50%" @close="addCateDialogClosed">
      <!-- 对话框: 内容主题区 -->
      <el-form ref="addCateFormRef" :model="newCate" :rules="addCateRules" label-width="80px" label-position="right">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="newCate.cat_name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            :options="parentCateList"
            clearable
            :props="cascaderProps"
            v-model="selectedKeys"
            @change="parentCateChanged"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <!-- 对话框: 底部区域 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddCateForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- "修改分类"对话框 -->
    <el-dialog title="修改分类" :visible.sync="eidtCateDialogVisible" width="50%" @close="editCateDialogClosed">
      <!-- 对话框: 内容主题区 -->
      <el-form ref="editCateFormRef" :model="editCate" :rules="addCateRules" label-width="80px" label-position="right">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCate.cat_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框: 底部区域 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="eidtCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditCateForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 控制"添加分类"对话框的显示
      addCateDialogVisible: false,
      // 获取商品分类列表的参数对象
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 商品分类列表
      cateList: [],
      // 1,2级商品分类列表
      parentCateList: [],
      // 总数据条数
      total: 0,
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          type: 'template', // 将当前列定义为模板列
          template: 'isok' // 当前列使用的模板名称
        },
        {
          label: '排序',
          type: 'template',
          template: 'order'
        },
        {
          label: '操作',
          type: 'template',
          template: 'action'
        }
      ],
      // "添加分类" 表单数据对象
      newCate: {
        cat_name: '',
        cat_pid: '0',
        cat_level: '0'
      },
      // "添加分类" 校验规则
      addCateRules: {
        cat_name: [
          { required: true, message: '分类名称不能为空', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 10 个字符', trigger: 'blur' },
          { whitespace: true, message: '不能为空格', trigger: 'blur' }
        ]
      },
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
        // 选择任意一级
        checkStrictly: true
      },
      // 选中的父级分类的id数组
      selectedKeys: [],
      // 控制"修改分类"对话框的显示
      eidtCateDialogVisible: false,
      editCate: {}
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data.result
      this.total = res.data.total
    },
    // 监听pagesize改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getCateList()
    },
    // 监听pagenum改变的事件
    handleCurrentChange(newPagenum) {
      this.queryInfo.pagenum = newPagenum
      this.getCateList()
    },
    // 监听"添加分类"对话框关闭事件
    addCateDialogClosed() {
      this.$refs.addCateFormRef.resetFields()
      this.selectedKeys = []
      this.newCate = {
        cat_name: '',
        cat_pid: '0',
        cat_level: '0'
      }
      this.getCateList()
    },
    // 显示"添加分类"对话框
    async showAddCateDialog() {
      // 查询所有分类
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.parentCateList = res.data
      this.addCateDialogVisible = true
    },
    parentCateChanged() {
      if (this.selectedKeys.length > 0) {
        this.newCate.cat_pid = this.selectedKeys[this.selectedKeys.length - 1] + ''
        this.newCate.cat_level = this.selectedKeys.length + ''
        return
      } else {
        this.newCate.cat_pid = '0'
        this.newCate.cat_level = '0'
      }
      console.log(this.newCate)
    },
    // 提交"添加分类"表单
    submitAddCateForm() {
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.post('categories', this.newCate)
        if (res.meta.status !== 201) {
          return this.$message.error('添加分类失败!')
        }
        this.$message.success('添加分类成功!')
        this.addCateDialogVisible = false
      })
    },
    editCateDialogClosed() {
      this.$refs.editCateFormRef.resetFields()
      this.editCate = {}
      this.getCateList()
    },
    // 显示"修改分类"对话框
    async showEditCateDialog(id) {
      console.log(id)
      const { data: res } = await this.$http.get('categories/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      console.log(res)
      this.editCate = res.data
      this.eidtCateDialogVisible = true
    },
    // 提交"修改分类"表单
    submitEditCateForm() {
      this.$refs.editCateFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        console.log(this.editCate)
        const { data: res } = await this.$http.put('categories/' + this.editCate.cat_id, {
          cat_name: this.editCate.cat_name
        })
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.eidtCateDialogVisible = false
      })
    },
    // 删除分类
    async deleteCate(cate) {
      const result = await this.$messageBox
        .confirm('此操作将删除分类: ' + cate.cat_name + ', 是否继续?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        })
        .catch(err => err)
      if (result !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('categories/' + cate.cat_id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getCateList()
    }
  }
}
</script>

<style lang="less" scoped>
.tree-table {
  margin-top: 20px;
  margin-bottom: 20px;
  font-size: 14px;
}
</style>
